package com.founder.android.db;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class LocationStoreService extends BaseStoreService {

	public LocationStoreService(SQLiteDatabase db) {
		super(db);
	}
	
	public void saveLocation(Location location) {
		Location dbLocation = find();
		if (dbLocation == null) {
			db.execSQL("INSERT INTO location(id, name, lat, lng) VALUES(1,?,?,?)", 
					new Object[] {location.getName(), location.getLat(), location.getLng()});
		} else {
			db.execSQL("UPDATE location SET name=?, lat=?, lng=? WHERE id=?", 
					new Object[] {location.getName(), location.getLat(), location.getLng(), dbLocation.getId()});
		}
	}
	
	public Location find() {
		Location location = null;
		Cursor cursor = db.rawQuery("SELECT * FROM location WHERE id=?", 
				new String[] { "1" });
		try {
			if (cursor.moveToNext()) {
				location = initLocation(cursor);
			}
		} finally {
			cursor.close();
		}
		return location;
	}
	
	private Location initLocation(Cursor cursor) {
		Integer id = cursor.getInt(cursor.getColumnIndex("id"));
		String name = cursor.getString(cursor.getColumnIndex("name"));
		Double lat = cursor.getDouble(cursor.getColumnIndex("lat"));
		Double lng = cursor.getDouble(cursor.getColumnIndex("lng"));
		return new Location(id, name, lat, lng);
	}

}
